<template>
  <div class="app-container">

    <div class="group-list-container">
      <div class="menu el-col-14">
        <el-button type="default" @click="addGroup">添加</el-button>
      </div>
      <div class="search el-col-10">
        <el-input placeholder="搜索关键字" v-model="params.name" @keyup.enter.native="searchClick" class="input-with-select">
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
      </div>

      <!-- 主视角数据列表 -->
      <el-table :data="groupList" border style="width: 100%" element-loading-text="拼命加载中">
        <el-table-column fixed="left" sortable align="center" prop="name" min-width="120" label="组名"></el-table-column>
        <el-table-column align="center" label="组成员" prop="member" min-width="120">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleMemberEdit(scope.row.id)">{{'成员列表（' + scope.row.member+ '）人'}}</el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" label="前端权限" min-width="120">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleEditMenu(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="text" @click="handleViewMenu(scope.row.id)">查看</el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" label="组操作" min-width="120">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="text" @click="handleSubmitDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pageination" v-show="total>5">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :page-sizes="[5, 10, 15, 20]"
          :current-page.sync="params.page"
          :page-size="params.page_size"
          :total="total">
        </el-pagination>
      </div>

      <!-- 新增项目对话框 -->
      <el-dialog title="新增用户组" :visible.sync="dialogTableAddVisible" width="936px">
        <el-form :model="groupItem" status-icon :rules="rules" ref="groupForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="用户组" prop="name">
            <el-input type="text" v-model="groupItem.name" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="权限" prop="permissions">
            <div class="transfer-box">
              <el-transfer
                v-model="groupItem.permissions"
                filterable
                :titles="['未授权限', '已有权限']"
                :format="{
                  noChecked: '${total}',
                  hasChecked: '${checked}/${total}'
                }"
                :data="permissionList">
                <span slot-scope="{ option }">{{ option.label }}</span>
              </el-transfer>
            </div>
          </el-form-item>
          <el-form-item class="btn-wrapper">
            <el-button size="small" @click="resetGroupForm">关闭</el-button>
            <el-button size="small" :loading="isLoading" type="primary" @click="submitAddGroupForm(groupItem)">添加</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

      <!-- 编辑项目对话框 -->
      <el-dialog title="编辑用户组" :visible.sync="dialogTableEditVisible" width="936px">
        <el-form :model="editGroupItem" status-icon :rules="rules" ref="groupForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="用户组" prop="name">
            <el-input type="text" v-model="editGroupItem.name" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="权限" prop="permissions">
            <div class="transfer-box">
              <el-transfer
                v-model="editGroupItem.permissions"
                filterable
                :titles="['未授权限', '已有权限']"
                :format="{
                  noChecked: '${total}',
                  hasChecked: '${checked}/${total}'
                }"
                :data="permissionList">
                <span slot-scope="{ option }">{{ option.label }}</span>
              </el-transfer>
            </div>
          </el-form-item>
          <el-form-item class="btn-wrapper">
            <el-button size="small" @click="resetGroupForm">关闭</el-button>
            <el-button size="small" :loading="isLoading" type="primary" @click="submitEditGroupForm(editGroupItem)">修改</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

      <!-- 组成员弹窗 -->
      <el-dialog title="组成员列表" :visible.sync="dialogTableMemberVisible" width="60%">
        <div class="search-row">
          <el-input placeholder="搜索关键字" v-model="member_params.name" @keyup.enter.native="memberSearchClick" class="input-with-select">
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </div>
        <el-table :data="members" border style="width: 100%" element-loading-text="拼命加载中">
          <el-table-column sortable align="center" prop="username" label="用户名"></el-table-column>
          <el-table-column sortable align="center" prop="name" label="姓名"></el-table-column>
          <el-table-column sortable align="center" min-width="140" prop="email" label="邮箱"></el-table-column>
          <el-table-column sortable align="center" min-width="130" prop="last_login" label="登陆时间"></el-table-column>
          <el-table-column sortable align="center" label="操作">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="handleDeleteMember(scope.row)">移出</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>

      <!-- 查看前端菜单 -->
      <el-dialog :title="menuTitle" :visible.sync="groupMenuVisible" width="400px">
        <el-tree
          :v-loading="isLoading"
          :data="menuData"
          :show-checkbox="menuFlag"
          default-expand-all
          node-key="id"
          ref="tree"
          highlight-current
          :default-checked-keys="defaultCheckedKeys">
        </el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button size="small" @click="groupMenuVisible=false">取 消</el-button>
          <el-button size="small" type="primary" @click="submitGroupMenus">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import { getGroupList, createGroup, deleteGroup, updateGroup,
    getGroupMembers, deleteGroupMember, getGroupMenuList,
    updateGroupMenu, getPermissionsList } from '@/api/users'
  export default {
    name: 'users',
    data() {
      return {
        dialogTableAddVisible: false,
        dialogTableEditVisible: false,
        dialogTableMemberVisible: false,
        dialogVisibleDrop: false,
        PermissionVisible: false,
        groupList: [],
        isLoading: false,
        groupItem: {
          name: ''
        },
        editGroupItem: {
          id: 0,
          name: ''
        },
        rules: {
          name: [{ required: true, message: '用户组名称不能为空', trigger: 'blur' }]
        },
        total: 0,
        params: {
          page: 1,
          page_size: 10,
          name: ''
        },
        // 组成员需要变量
        members: [], // 组成员弹窗列表
        groupID: '',
        member_params: {
          name: '',
          page: 1
        },
        // 接口权限变量
        permissionList: [],
        // 前端菜单变量
        menuTitle: '',
        groupMenuVisible: false,
        menuData: [],
        menuFlag: false,
        defaultCheckedKeys: [],
        menuModifyData: {
          gid: 0, // 当前修改的组id
          mid: [] //
        }
      }
    },
    created() {
      this.fetchData()
      this.getPermissions()
    },
    methods: {
      fetchData() {
        getGroupList(this.params).then(res => {
          this.groupList = res.results
          this.total = res.count
        })
      },
      /* 获取组员 */
      fetchGroupMembers() {
        getGroupMembers(this.groupID, this.member_params).then(
          ret => {
            this.members = ret.results
          }
        )
      },
      /* 获取权限列表 */
      getPermissions() { // 获取权限数据列表
        getPermissionsList().then(
          res => {
            this.permissionList = res.map(
              item => {
                return { key: item.id, label: item.perm_name, disabled: false }
              })
          }).catch(
          () => {
            this.$message.error('获取权限数据失败')
          }
        )
      },
      /* 分页 改变页码和页面大小时获取对应的数据 */
      handleCurrentChange(val) {
        this.params.page = val
        this.fetchData()
      },
      handleSizeChange(val) {
        this.params.page_size = val
        this.fetchData()
      },
      /* 搜索 */
      searchClick() {
        this.params.page = 1
        this.fetchData()
      },
      /* 添加组 */
      addGroup() {
        this.dialogTableAddVisible = true
      },
      resetGroupForm() {
        this.dialogTableAddVisible = false
        this.dialogTableEditVisible = false
        this.groupItem = { name: '' }
        this.$refs.groupForm.resetFields()
      },
      submitAddGroupForm() {
        this.isLoading = true
        createGroup(this.groupItem).then(
          () => {
            this.isLoading = false
            this.resetGroupForm()
            this.$message.success('创建用户组成功')
            this.fetchData()
          }).catch(
          () => {
            console.log(this.groupItem)
            this.isLoading = false
            this.resetGroupForm()
            this.$message.error('创建用户组失败')
          }
        )
      },
      /* 编辑权限、删除组或组员 */
      handleEdit(value) {
        this.dialogTableEditVisible = true
        this.editGroupItem = { ...value }
      },
      handleSubmitDelete(value) {
        this.$confirm(`确认删除用户组 ${value.name} 吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(
          () => {
            if (value.member === 0) {
              deleteGroup(value.id).then(
                () => {
                  // this.isLoading = false
                  this.fetchData()
                  this.$message.success('删除用户组成功')
                })
            } else {
              this.$message.error('删除失败，请先移出用户组下的用户')
            }
          }).catch(
          () => {
            this.$message.info('已取消删除')
          })
      },
      submitEditGroupForm(value) {
        const { id, ...data } = value
        this.isLoading = true
        updateGroup(id, data).then(
          () => {
            this.isLoading = false
            this.dialogTableEditVisible = false
            this.resetGroupForm()
            this.fetchData()
            this.$message.success('修改用户组成功')
          }
        )
      },
      handleMemberEdit(id) {
        this.groupID = id
        this.fetchGroupMembers()
        this.dialogTableMemberVisible = true
      },
      handleDeleteMember(user) {
        this.$confirm('此操作将移出组成员 “' + user.name + '” , 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteGroupMember(this.groupID, { uid: user.id }).then(
            () => {
              this.$message.success('移出组成员 “' + user.name + '” 成功')
              this.fetchGroupMembers()
              this.fetchData()
            })
        }).catch(() => { })
      },
      memberSearchClick() {
        this.member_params.page = 1
        this.fetchGroupMembers()
        this.member_params.name = ''
      },
      /* 前端菜单 */
      handleViewMenu(gid) {
        this.menuTitle = '查看菜单权限'
        this.menuData = []
        this.menuFlag = false
        this.groupMenuVisible = true
        this.isLoading = true
        getGroupMenuList(gid).then(
          res => {
            this.menuData = res
            this.isLoading = false
          }
        )
      },
      handleEditMenu(gid) {
        this.menuTitle = '编辑菜单权限'
        this.menuData = []
        this.isLoading = true
        this.menuFlag = true
        this.groupMenuVisible = true
        this.menuModifyData.gid = gid
        this.defaultCheckedKeys = []
        getGroupMenuList(gid, { modify: true }).then(
          res => {
            this.menuData = res.data
            this.defaultCheckedKeys = res.permissions
            this.isLoading = false
          })
      },
      submitGroupMenus() {
        if (!this.menuFlag) {
          this.groupMenuVisible = false
          return
        }
        const mids = this.$refs.tree.getCheckedKeys()
        updateGroupMenu(this.menuModifyData.gid, { mid: mids }).then(
          () => {
            this.groupMenuVisible = false
            this.$message.success('操作成功')
          }
        )
      }
    }
  }
</script>

<style lang="scss">
  .group-list-container {
    .btn-wrapper {
      text-align: right;
    }
    .search-row {
      margin-bottom: 10px;
    }

    .transfer-box {
      text-align: left;
      .el-transfer {
        width: 100%;
        text-align: left;
        display: inline-block;
        .el-transfer-panel {
          width: 350px;
        }
      }
    }
  }
</style>
